package com.lingz.manager.modules.scheduled;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.lingz.manager.modules.wuxue.entity.WaterConservancyData;
import com.lingz.manager.modules.wuxue.mapper.WaterConservancyDataMapper;
import com.lingz.manager.modules.wuxue.utils.DeviceDataUtil;
import com.lingz.manager.modules.wuxue.utils.SendRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Classname WaterConservancyDataTask
 * @Description TODO
 * @Date 2023/12/8 15:35
 * @Created by mjh
 */
@Component
@Slf4j
public class WaterConservancyDataTask {
    @Value("${waterConservancy.djgq}")
    String djgq;

    @Value("${waterConservancy.jzgq}")
    String jzgq;

    @Value("${waterConservancy.xrbgq}")
    String xrbgq;
    @Autowired
    WaterConservancyDataMapper waterConservancyDataMapper;

    @Scheduled(cron = "0 0 0/1 * * ?")
    public void waterConservancyDataAdd() {
        SendRequest request = new SendRequest();
        ArrayList<String> urls = new ArrayList<>();
        urls.add(djgq);
        urls.add(jzgq);
        urls.add(xrbgq);
        urls.forEach(url -> {
            String jsonResponse = request.sendGet(url);

            JSONArray data = JSONArray.parseArray(jsonResponse);
            List<WaterConservancyData> waterConservancyDataList = new ArrayList<>();
            if(data!= null && !data.isEmpty()){
                for(int i = 0 ; i <data.size(); i++){
                    JSONObject jsonObject = data.getJSONObject(i);
                    String stname = jsonObject.getString("stname");
                    JSONObject flowVO = jsonObject.getJSONObject("flowVO");
                    if(flowVO != null) {
                        try {
                            WaterConservancyData waterConservancyData = DeviceDataUtil.parseJsonToWaterConservancyData(flowVO, stname);
                            if(waterConservancyData != null)
                                waterConservancyDataList.add(waterConservancyData);
                        } catch (ParseException e) {
                            throw new RuntimeException(e);
                        }
                    }
                }
            }
            waterConservancyDataMapper.insertBatchSomeColumn(waterConservancyDataList);
        });
        log.info("插入水利设备监测数据成功");
    }
}
